<template>
  <a-breadcrumb
    class="breadcrumb-list"
  >
    <a-breadcrumb-item
      v-for="(item, index) in routeMatcheds?.breadcrumbs"
      :key="index">
      <span class="nagavitor-item" @click="nagavitorAndChangeRouter(item, index)">
        <component v-if="item.path === '/'" :is="$antIcons['HomeOutlined']" />
        {{ item.meta?.title || 'meta必须配置title' }}
      </span>
      </a-breadcrumb-item>
  </a-breadcrumb>
</template>
<script lang="ts">
import { mapState, useStore } from 'vuex'
import { defineComponent, reactive, watchEffect} from 'vue'
import { mutations } from '../../store/types'
import { menus as Menus, matchedBox, route } from '@/utils/interface'
import { useRoute } from 'vue-router'

export default defineComponent({
  setup () {
    const store = useStore()
    const route = useRoute()
    let routeMatcheds: matchedBox = reactive({
      breadcrumbs: []
    })
    routeMatcheds.breadcrumbs = route.matched
    watchEffect(() => {
      routeMatcheds.breadcrumbs = route.matched
    })
    return { store, routeMatcheds }
  },
  computed: {
    ...mapState('system', ['menus'])
  },
  methods: {
    // 根据路由的name获取到菜单项的id --- 对应到menus 上  name === path
    getMenuIdByName (name: string) {
      const menus = this.menus
      let menuId: string = '';
      let deepLoop = (arr: Menus[]) => {
        for (let i = 0; i < arr.length; i++) {
          if (arr[i]?.path === name) {
            menuId = arr[i].id
            break
          }
          if (arr[i]?.children?.length) {
            deepLoop(arr[i]?.children ?? [])
          }
        }
      }
      deepLoop(menus)
      return menuId
    },
    // 跳转至对应的路由以及设置当前选中内容
    nagavitorAndChangeRouter (route: route, index: number) {
      if (index === this.routeMatcheds?.breadcrumbs.length - 1) {
        return false
      }
      this.store.commit(`system/${mutations.system.selectedKeys}`, [this.getMenuIdByName(route.name)])
      this.$router.push({ name: route.name })
    }
  }
})
</script>
<style lang="scss" scoped>
.breadcrumb-list {
  position: fixed;
  top: 64px;
  padding: 20px 0 0 20px;  
}
.nagavitor-item {
  cursor: pointer;
}
</style>